package com.sheng.leetcode.year2022.swordfingeroffer.day18;

import org.junit.Test;

/**
 * @author liusheng
 * @date 2022/09/16
 *<p>
 * 剑指 Offer 55 - II. 平衡二叉树<p>
 *<p>
 * 输入一棵二叉树的根节点，判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1，那么它就是一棵平衡二叉树。<p>
 *<p>
 * 示例 1:<p>
 * 给定二叉树 [3,9,20,null,null,15,7]<p>
 *<p>
 *     3<p>
 *    / \<p>
 *   9  20<p>
 *     /  \<p>
 *    15   7<p>
 * 返回 true 。<p>
 *<p>
 * 示例 2:<p>
 * 给定二叉树 [1,2,2,3,3,null,null,4,4]<p>
 *<p>
 *        1<p>
 *       / \<p>
 *      2   2<p>
 *     / \<p>
 *    3   3<p>
 *   / \<p>
 *  4   4<p>
 * 返回false 。<p>
 *<p>
 * 限制：<p>
 *<p>
 * 0 <= 树的结点个数 <= 10000<p>
 * 注意：本题与主站 110题相同：<a href="https://leetcode-cn.com/problems/balanced-binary-tree/">...</a><p>
 *<p>
 * 来源：力扣（LeetCode）<p>
 * 链接：<a href="https://leetcode.cn/problems/ping-heng-er-cha-shu-lcof">...</a><p>
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。<p>
 */
public class Sword0055Two {

    @Test
    public void test01() {
        TreeNode root = new TreeNode(3);
        TreeNode right = new TreeNode(20);
        right.left = new TreeNode(15);
        right.right = new TreeNode(7);
        root.left = new TreeNode(9);
        root.right = right;

//        TreeNode root = new TreeNode(1);
//        TreeNode left = new TreeNode(2);
//        TreeNode left1 = new TreeNode(3);
//        left1.left = new TreeNode(4);
//        left1.right = new TreeNode(4);
//        left.left = left1;
//        left.right = new TreeNode(3);
//        root.left = left;
//        root.right = new TreeNode(2);
        System.out.println(new Solution55Two().isBalanced(root));
    }
}
class Solution55Two {
    boolean flag = true;
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        // 递归
        int left = getHeight(root.left, 1);
        int right = getHeight(root.right, 1);
        // 当前结点高度差是否小余等于1，并且子节点是否也全部都满足该条件
        return Math.abs(left - right) <= 1 && flag;
    }

    public int getHeight(TreeNode node, int height) {
        if (node == null) {
            return height;
        }
        height++;
        int left = getHeight(node.left, height);
        int right = getHeight(node.right, height);
        if (flag) {
            flag = Math.abs(left - right) <= 1;
        }
        return Math.max(left, right);
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
